#include <stdio.h>		// tmpnam() / popen(,)
#include <stdlib.h>		// getenv()
#include <process.h>	// system()
#include <string.h>
#include <Windows.h>	// Sleep()
#include "Exec.h"

#ifdef _WIN32
#ifdef _DEBUG
   #include <crtdbg.h>
   #undef THIS_FILE
   static char THIS_FILE[] = __FILE__;
   #define new       new( _NORMAL_BLOCK, __FILE__, __LINE__)
   #define malloc(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#endif


// Constructor
Exec::Exec(char *command) {
	output = _popen(command, "r");
}

// Deconstructor
Exec::~Exec() {
	_pclose(output);
}

// whether or not there is output to parse
bool Exec::isOutput() {
	return (output != NULL);
}

// reads off next line from stdout, and chops off \r\n
char* Exec::getNext() {
	// if there is no data
	if(!isOutput()) {
		return NULL;
	}

	// get the next line of output
	if(fgets(buffer, DEFAULT_BUFLEN, output) == NULL) {
		return NULL;
	}

	// remove \r\n
	if(strstr(buffer, "\n")) {
		buffer[strlen(buffer)-1] = 0;
	}
	if(strstr(buffer, "\r")) {
		buffer[strlen(buffer)-1] = 0;
	}

	return buffer;
}